package cn.edu.zafu.bigdata.lwg;

import java.io.*;
import java.net.*;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        // 创建一个DatagramSocket，监听端口号1234
        DatagramSocket serverSocket = new DatagramSocket(8888);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];

        while (true) {
            // 创建一个DatagramPacket，用于接收客户端发送的数据
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

            // 获取当前时间
            String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());

            // 将时间信息放入sendData
            System.arraycopy(currentTime.getBytes(), 0, sendData, 0, sendData.length);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
            serverSocket.send(sendPacket);
        }
    }
}

class UDPClient {
    public static void main(String[] args) throws IOException {
        // 创建一个DatagramSocket
        DatagramSocket clientSocket = new DatagramSocket();
        // 要发送的数据
        String data = "Time Request";
        byte[] sendData = data.getBytes();
        byte[] receiveData = new byte[1024];

        // 服务端的IP地址和端口号
        InetAddress IPAddress = InetAddress.getByName("192.168.16.73");
        int port = 8888;

        // 创建一个DatagramPacket，用于发送数据到服务端
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        // 发送数据
        clientSocket.send(sendPacket);

        // 创建一个DatagramPacket，用于接收服务端返回的数据
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        // 接收数据
        clientSocket.receive(receivePacket);
        // 将接收到的数据转换成字符串
        String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
        // 打印服务端返回的时间
        System.out.println("从服务器接收到的时间是: " + received);

    }
}